package org.springframework.license.listener;

import org.springframework.license.exception.LicenseException;
import org.springframework.license.properties.LicenseProperties;
import org.springframework.license.validate.LicenseVerify;
import org.springframework.license.vo.LicenseVerifyParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * @Title LicenseCheckListener
 * @Author zhijun.Guo
 * @Email tiankong061015@163.com
 * @Time 2024/9/3 00:29
 * @Description
 */
@Slf4j
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {

    private final LicenseProperties properties;

    public LicenseCheckListener(LicenseProperties properties) {
        this.properties = properties;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //root application context 没有parent
        try {
            ApplicationContext context = event.getApplicationContext().getParent();
            if(context == null){
                if(StringUtils.isNotBlank(properties.getLicensePath())){
                log.info("++++++++ 开始安装证书 ++++++++");

                LicenseVerifyParam param = new LicenseVerifyParam();
                param.setSubject(properties.getSubject());
                param.setPublicAlias(properties.getPublicAlias());
                param.setStorePass(properties.getStorePass());
                param.setLicensePath(properties.getLicensePath());
                param.setPublicKeysStorePath(properties.getPublicKeysStorePath());

                LicenseVerify licenseVerify = new LicenseVerify();
                //安装证书
                licenseVerify.install(param);

                log.info("++++++++ 证书安装结束 ++++++++");
                }
            }
        } catch (LicenseException ex){
          log.error(ex.getMessage());
        } catch (Exception e){
            log.error(e.getMessage());
        }
    }
}
